package com.dodock.android.banglapapers.db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.dodock.android.banglapapers.BanglaNews;
import com.dodock.android.banglapapers.Category;
import com.dodock.android.banglapapers.NewsDetails;

public class DatabaseManager extends SQLiteOpenHelper {
	
	private static String DB_PATH;
	private static String DB_NAME = "banglapapers.db3";
	private SQLiteDatabase db;
	private final Context context;
	public final int ORDER_RANDOM = -1;
	public final int ORDER_ASCENDING = 1;
	public final int ORDER_DESCENDING = 2;
	public final int ORDER_CURRENT = 0;

	public DatabaseManager(Context context) {
		super(context, DB_NAME, null, 1);
		this.context = context;

		DatabaseManager.DB_PATH = BanglaNews.getFilePath() + "/";
		if (!checkDataBase()) {
			try {
				copyDataBase();
			} catch (IOException e) {
				Log.e("DatabaseManager1", e.toString());
			}
		}
	}

	private void copyDataBase() throws IOException {
		
		// Open your local db as the input stream
		InputStream myInput = context.getAssets().open(DB_NAME);

		// Path to the just created empty db
		String outFileName = DB_PATH + DB_NAME;

		// Open the empty db as the output stream
		new File(outFileName).createNewFile();
		OutputStream myOutput = new FileOutputStream(outFileName);

		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}
		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	public void closeDB() {
		db.close();
	}

	public void initializeDatabase() {
		try {
			db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null,
					SQLiteDatabase.OPEN_READWRITE
							| SQLiteDatabase.NO_LOCALIZED_COLLATORS);
		} catch (Exception ex) {
			ex.printStackTrace();
			Log.e("DatabaseManager", "initializeDatabase() : "+ex.toString());
		}
	}

	public boolean checkDataBase() {
		String myPath = DB_PATH + DB_NAME;
		if (new File(myPath).exists())
			return true;
		else
			return false;
	}

	public void addCategoryDB(ContentValues cv) {
		db.insert("favorite", null, cv);
	}

	public boolean isCategoryExist(String paper_key) {
		boolean exist;
		Cursor cursor;
		String sql = "SELECT * FROM favorite WHERE paper_key='" + paper_key
				+ "'";
		cursor = db.rawQuery(sql, null);
		if (cursor.getCount() > 0)
			exist = true;
		else
			exist = false;
		cursor.close();
		return exist;
	}

	public boolean isNewsSaved(String paperid_newsid) {
		boolean exist;
		Cursor cursor;
		String sql = "SELECT * FROM news WHERE paperid_newsid=?";
		cursor = db.rawQuery(sql, new String[] { paperid_newsid });
		if (cursor.getCount() > 0)
			exist = true;
		else
			exist = false;
		cursor.close();
		return exist;
	}

	public void removeCategory(String paper_key) {
		db.delete("favorite", "paper_key=?", new String[] { paper_key });
	}

	public void deleteSavedNews(String paperid_newsid) {
		db.delete("news", "paperid_newsid=?", new String[] { paperid_newsid });
	}

	public void addNewsDB(String paperid, String newsid, String sharelink,
			String newsdetails, boolean galleryflag,
			Vector<String> galleryList, String title, String language) {
		if (galleryflag) {
			addGalleryToDb(galleryList, paperid + newsid);
		}
		ContentValues cv = new ContentValues();
		cv.put("newsid", newsid);
		cv.put("paperid", paperid);
		cv.put("paperid_newsid", paperid + newsid);
		cv.put("sharelink", sharelink);
		cv.put("newsdetails", newsdetails);
		cv.put("title", title);
		cv.put("language", language);
		db.insert("news", null, cv);
	}

	public void addGalleryToDb(Vector<String> galleryList, String paperid_newsid) {
		for (int i = 0; i < galleryList.size(); i++) {
			ContentValues cv = new ContentValues();
			cv.put("image", galleryList.elementAt(i));
			cv.put("paperid_newsid", paperid_newsid);
			db.insert("gallery", null, cv);
		}
	}

	public Vector<Category> getCategoriesOfPaper(String paper) {
		Vector<Category> categoryList = new Vector<Category>();
		Category category;
		Cursor cursor;
		String sql = "SELECT * FROM favorite WHERE paper=?";
		cursor = db.rawQuery(sql, new String[] { paper });
		if (cursor.moveToFirst()) {
			do {
				category = new Category();
				category.setKey(cursor.getString(cursor
						.getColumnIndex("key")));
				category.setPaperName(cursor.getString(cursor
						.getColumnIndex("paper")));
				category.setDisplay(cursor.getString(cursor
						.getColumnIndex("display")));
				categoryList.add(category);
			} while (cursor.moveToNext());
		}
		cursor.close();
		return categoryList;
	}

	public boolean isGalleryExist(String paperid_newsid) {
		boolean exist;
		Cursor cursor;
		String sql = "SELECT * FROM gallery WHERE paperid_newsid='"
				+ paperid_newsid + "'";
		cursor = db.rawQuery(sql, null);
		if (cursor.getCount() > 0)
			exist = true;
		else
			exist = false;
		cursor.close();
		return exist;
	}

	public Vector<String> getGalleryList(String paperid_newsid) {
		Vector<String> galleryList = new Vector<String>();

		Cursor cursor;
		String sql = "SELECT * FROM gallery WHERE paperid_newsid=?";
		cursor = db.rawQuery(sql, new String[] { paperid_newsid });
		if (cursor.moveToFirst()) {
			do {
				galleryList.add(cursor.getString(cursor
						.getColumnIndex("image")));
			} while (cursor.moveToNext());
		}
		cursor.close();
		return galleryList;
	}

	public Vector<NewsDetails> getSavedNewsOfPaper(String paperid) {
		Vector<NewsDetails> savednewsList = new Vector<NewsDetails>();
		NewsDetails category;
		Cursor cursor;
		String sql = "SELECT * FROM news WHERE paperid=?";
		cursor = db.rawQuery(sql, new String[] { paperid });
		if (cursor.moveToFirst()) {
			do {
				category = new NewsDetails();
				String newsid = cursor.getString(cursor
						.getColumnIndex("newsid"));
				category.setId(newsid);
				if (isGalleryExist(paperid + newsid)) {
					category.setGalleryFlag(true);
					category.setGalleryUrlList(getGalleryList(paperid + newsid));
				} else {
					category.setGalleryFlag(false);
				}
				category.setSharelink(cursor.getString(cursor
						.getColumnIndex("sharelink")));
				category.setTitle(cursor.getString(cursor
						.getColumnIndex("title")));
				category.setDetailsNews(cursor.getString(cursor
						.getColumnIndex("newsdetails")));
				category.setPaperId(cursor.getString(cursor
						.getColumnIndex("paperid")));
				category.setLanguage(cursor.getString(cursor
						.getColumnIndex("language")));				
				savednewsList.add(category);
			} while (cursor.moveToNext());
		}
		cursor.close();
		return savednewsList;
	}

	public Vector<NewsDetails> getTotalSavedNewsList() {
		Vector<NewsDetails> savednewsList = new Vector<NewsDetails>();
		NewsDetails category;
		Cursor cursor;
		String sql = "SELECT * FROM news";
		cursor = db.rawQuery(sql, null);
		if (cursor.moveToFirst()) {
			do {
				category = new NewsDetails();
				String newsid = cursor.getString(cursor
						.getColumnIndex("newsid"));
				category.setId(newsid);
				String paperid = cursor.getString(cursor
						.getColumnIndex("paperid"));
				category.setPaperId(paperid);
				if (isGalleryExist(paperid + newsid)) {
					category.setGalleryFlag(true);
					category.setGalleryUrlList(getGalleryList(paperid + newsid));
				} else {
					category.setGalleryFlag(false);
				}
				category.setSharelink(cursor.getString(cursor
						.getColumnIndex("sharelink")));
				category.setTitle(cursor.getString(cursor
						.getColumnIndex("title")));
				category.setDetailsNews(cursor.getString(cursor
						.getColumnIndex("newsdetails")));
				category.setPaperId(cursor.getString(cursor
						.getColumnIndex("paperid")));
				category.setLanguage(cursor.getString(cursor
						.getColumnIndex("language")));
				savednewsList.add(category);
			} while (cursor.moveToNext());
		}
		cursor.close();
		return savednewsList;
	}

}
